/*
 *      Copyright (c) 2018-2028, DreamLu All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: DreamLu 卢春梦 (596392912@qq.com)
 */
package com.plian.Tools;

import org.springframework.lang.Nullable;

import java.lang.reflect.Field;
import java.lang.reflect.Type;

/**
 * 对象工具类
 *
 * @author L.cm
 */
public class ObjectUtil extends org.springframework.util.ObjectUtils {

    /**
     * 判断元素不为空
     *
     * @param obj object
     * @return boolean
     */
    public static boolean isNotEmpty(@Nullable Object obj) {
        return !ObjectUtil.isEmpty(obj);
    }

    /**
     * 判断对象是否为空，且对象的所有属性都为空
     * ps: boolean类型会有默认值false 判断结果不会为null 会影响判断结果
     * 序列化的默认值也会影响判断结果
     *
     * @param object
     * @return
     */
    public static boolean objIsNull(Object object) {
        Class clazz = object.getClass();
        Field fields[] = clazz.getDeclaredFields();
        //定义标志flag
        boolean flag = true;
        /**
         * 循环遍历反射得到的属性数组，判断每个属性值是否为空
         */
        for (Field f : fields) {
            //由于考虑到某些私有属性直接访问肯能访问不到，此属性设置为true确保可以访问到
            f.setAccessible(true);
            Object fieldValue = null;
            try {
                //得到属性值
                fieldValue = f.get(object);
                //得到属性类型
                Type fieldType = f.getGenericType();
                // 得到属性名
                String fieldName = f.getName();
                //System.out.println("属性类型：" + fieldType + ",属性名：" + fieldName + ",属性值：" + fieldValue);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            //只要有一个属性值不为null 就返回false 表示对象不为null
            if (fieldValue != null) {
                flag = false;
                break;
            }
        }
        return flag;
    }

}
